package com.longchat.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.longchat.controller.admin.BaseController;
import com.longchat.dto.award.WeixinUserInfo;
import com.longchat.dto.system.WeixinProperties;
import com.longchat.service.inter.weixin.IWechatService;
import com.longchat.utils.Rc4Utils;
import com.longchat.utils.WeiXinUrl;

@Controller
public class WeixinAuthController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(WeixinAuthController.class);
	@Autowired
	private WeixinProperties weixinProperties;
	@Autowired
	private IWechatService weixinService;
	
	@RequestMapping("/weixinAuth")
	public String weixinAuth(String resultUrl,HttpServletRequest request){
		logger.info("weixinAuth param==>resultUrl:{}",resultUrl);
		String redirectUrl = "";
		if(resultUrl!=null){
			try {
				redirectUrl = String.format(WeiXinUrl.GET_CODE, weixinProperties.getAppid(),URLEncoder.encode(getDomain(request)+"/"+request.getContextPath()+"/authorMeUrl?authUrl="+resultUrl,"utf-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		logger.debug("redirectUrl==>{}",redirectUrl);
		return "redirect:"+redirectUrl;
	}
	@RequestMapping("/authorMeUrl")
	public String authorMeUrl(String authUrl,String code,HttpServletResponse response){
		logger.info("authorMeUrl:param==>code:{},url:{}",code,authUrl);
		 if (!"authdeny".equals(code)) {
			 String openid = weixinService.getOpenId(code);
			// WeixinUserInfo userInfo = weixinService.getUserInfo(openid);
			 String rc4EncodeOpenid = Rc4Utils.decry_RC4(openid+ENCRY_LAST_STR, Rc4Utils.KEY);
			 Cookie cookie = new Cookie("openid",rc4EncodeOpenid);
			// Cookie nickName = new Cookie("nickName", info.getNickname());
			 response.addCookie(cookie);
			 //response.addCookie(nickName);
		 }else{
			 return "/errorpage/404";
		 }
		return "redirect:"+authUrl;
	}
}
